package com.sgb.kjwl.viewmodel.enterprise;

import android.app.Application;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

import com.alibaba.fastjson.JSONObject;
import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.model.entity.Bean;
import com.sgb.kjwl.model.entity.enterprise.NeedListItemEntity;
import com.sgb.kjwl.model.entity.enterprise.TaxscaleEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.utils.PointUtils;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.util.UserOperating;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class AddNeed_ComPanyModel extends AndroidViewModel {
    public MutableLiveData<String> name = new MutableLiveData<>();
    public MutableLiveData<String> industry_type = new MutableLiveData<>();//行业类型
    public MutableLiveData<String> enterprise_type = new MutableLiveData<>();//企业类型
    public MutableLiveData<String> regist_path = new MutableLiveData<>();//注册地址
    public MutableLiveData<Boolean> taxreturns_normal = new MutableLiveData<>(false);//正常报税
    public MutableLiveData<Boolean> taxreturns_abnormal = new MutableLiveData<>(false);//不正常报税
    public MutableLiveData<String> taxscale = new MutableLiveData<>();//纳税规模
    public MutableLiveData<String> money = new MutableLiveData<>();
    public MutableLiveData<Boolean> is_bargaining = new MutableLiveData<>(false);
    public MutableLiveData<String> contacts_name = new MutableLiveData<>();
    public MutableLiveData<String> contacts_phone = new MutableLiveData<>();
    public MutableLiveData<String> need_content = new MutableLiveData<>();
    public MutableLiveData<String> need_remarks = new MutableLiveData<>();
    public MutableLiveData<String> toast_message = new MutableLiveData<>();


    public List<Bean> industry_type_list = new ArrayList<>();
    public List<Bean> enterprise_type_list = new ArrayList<>();
    public int enterprise_type_index = -1;
    public MutableLiveData<Integer> showloading_diag = new MutableLiveData<>();
    public MutableLiveData<Integer> showchoicepopwindow = new MutableLiveData<>();
    public List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> datas = new ArrayList<>();
    // 二级联动数据
    public List<List<AddressEntity<List<AddressEntity>>>> opt2 = new ArrayList<>();
    // 三级联动数据
    public List<List<List<AddressEntity>>> opt3 = new ArrayList<>();


    public List<TaxscaleEntity> taxscale_list = new ArrayList<>();
    public String taxScale_data = "";




    public int cityPosition1;
    public int cityPosition2;
    public int cityPosition3;

    public String districtNo;
    public String provinceNo;
    public String cityNo;

    public String industry_type_id = "";

    public NeedListItemEntity data = null;

    public String provinceName;
    public String cityName;
    public String areaName;

    public AddNeed_ComPanyModel(@NonNull Application application) {
        super(application);
        if(taxscale_list.size()==0){
            taxscale_list.add(new TaxscaleEntity("小规模"));
            taxscale_list.add(new TaxscaleEntity("一般纳税人"));
            taxscale_list.add(new TaxscaleEntity("出口纳税人"));
            taxscale_list.add(new TaxscaleEntity("未核税"));
        }
        if(enterprise_type_list.size()==0){
            enterprise_type_list.add(new Bean("有限责任公司"));
            enterprise_type_list.add(new Bean("个人独资公司"));
            enterprise_type_list.add(new Bean("港澳台公司"));
            enterprise_type_list.add(new Bean("集团公司"));
        }
    }


    public void subimtData(){


        if(TextUtils.isEmpty(name.getValue())){
            toast_message.postValue("请输入标题！");

            return;
        }
        if(TextUtils.isEmpty(industry_type.getValue())){
            toast_message.postValue("请选择行业类型!");

            return;
        }

        if(TextUtils.isEmpty(enterprise_type.getValue())){
            toast_message.postValue("请选择企业类型!");

            return;
        }

        if(!taxreturns_normal.getValue()&&!taxreturns_abnormal.getValue()){
            toast_message.postValue("请选择报税情况!");
            return;
        }
        if(TextUtils.isEmpty(taxscale.getValue())){
            toast_message.postValue("请选择纳税规模!");

            return;
        }

        if(TextUtils.isEmpty(money.getValue())&&!is_bargaining.getValue()){
            toast_message.postValue("请输入预算价格!");
            return;
        }


        if(TextUtils.isEmpty(contacts_name.getValue())){
            toast_message.postValue("请输入联系人姓名!");

            return;
        }


        if(TextUtils.isEmpty(contacts_phone.getValue())){
            toast_message.postValue("请输入联系电话!");
            return;
        }
        if (!CheckUtils.isMobileForService(contacts_phone.getValue())){
            toast_message.postValue("请输入正确的电话格式");
            return;
        }

        if(TextUtils.isEmpty(need_content.getValue())){

            toast_message.postValue("请输入需求说明内容");
            return;
        }


        Map<String,Object> map = new HashMap<>();
        map.put("demandTitle",name.getValue());

        map.put("industryTypeName",industry_type.getValue());
        map.put("industryTypeId",industry_type_id);
        map.put("enterpriseTypeName",enterprise_type.getValue());
        if(!TextUtils.isEmpty(provinceNo)) {
            JSONObject jsonObject = new JSONObject();
            if (!TextUtils.isEmpty(provinceName)) {
                jsonObject.put("provinceName", provinceName);
            }
            if (!TextUtils.isEmpty(provinceNo)) {
                jsonObject.put("provinceId", Long.parseLong(provinceNo));
            }
            if (!TextUtils.isEmpty(cityNo)) {
                jsonObject.put("cityId", Long.parseLong(cityNo));
            }
            if (!TextUtils.isEmpty(cityName)) {
                jsonObject.put("cityName", cityName);
            }
            if (!TextUtils.isEmpty(areaName)) {
                jsonObject.put("areaName", areaName);
            }
            if (!TextUtils.isEmpty(districtNo)) {
                jsonObject.put("areaId", Long.parseLong(districtNo));
            }
            map.put("registeredAddr", jsonObject.toJSONString());
        }else{
            map.put("registeredAddr","");
        }
        String taxReturns = "";
        if(taxreturns_normal.getValue()){
            taxReturns = "1";
        }
        if(taxreturns_abnormal.getValue()){
            taxReturns = "0";
        }
        if(taxreturns_normal.getValue()&&taxreturns_abnormal.getValue()){
            taxReturns = "1,0";
        }

        map.put("taxReturns",taxReturns);
        map.put("taxScale",taxScale_data);

        map.put("budgetPrice",is_bargaining.getValue()?"-1":money.getValue());
        map.put("linkman",contacts_name.getValue());
        map.put("linkmanPhone",contacts_phone.getValue());
        map.put("enterpriseTypeId",enterprise_type_index+"");

        map.put("requirementTypes",4);
        if(!TextUtils.isEmpty(need_remarks.getValue())){
            map.put("note",need_remarks.getValue());
        }
//        map.put("realName", UserOperating.getInstance().getUserInfo().getRealName());
        map.put("userAccount",SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_PHONE, ""));
        map.put("userNo","0");
        map.put("companyNo","0");
        map.put("teamNo","0");
        map.put("publishType", UserOperating.getInstance().isCompany()?1:UserOperating.getInstance().isTeam()?2:0);
        switch ((Integer) map.get("publishType")){
            case 1:
                map.put("companyNo",SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.COMPANY_NO,""));
                map.put("realName", SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.COMPANY_NAME,""));
                break;
            case 2:
                map.put("teamNo", SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.COMPANY_NO,""));
                map.put("realName", SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.COMPANY_NAME,""));
                break;

            case 0:
                map.put("userNo",SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.USER_NO,""));
                map.put("realName", SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.REAL_NAME,""));
                break;
        }
        map.put("demandType",0);
        map.put("specifications",need_content.getValue());
        showloading_diag.postValue(1);
        if(data!=null){

            map.put("id",data.getId());
            map.put("createUser",data.getCreateUser());
            try {
            data.setDemandTitle(name.getValue());
            data.setBudgetPrice(is_bargaining.getValue()?-1:Double.parseDouble(money.getValue()));
            data.setLinkman(contacts_name.getValue());
            data.setLinkmanPhone(contacts_phone.getValue());
            data.setNote(need_remarks.getValue());
            data.setSpecifications(need_content.getValue());
            data.setIndustryTypeName(map.get("industryTypeName").toString());
            data.setIndustryTypeId(map.get("industryTypeId").toString());
            data.setEnterpriseTypeName(map.get("enterpriseTypeName").toString());
            data.setRegisteredAddr(map.get("registeredAddr").toString());
            data.setTaxReturns(map.get("taxReturns").toString());
            data.setTaxScale(map.get("taxScale").toString());
            data.setEnterpriseTypeId(map.get("enterpriseTypeId").toString());

            }catch (Exception e){
                e.printStackTrace();
            }
            APIManager.getInstance().getNeedAPI().updateNeedMessage(map).enqueue(new Callback<BaseEntity<Object>>() {
                @Override
                public void onResponse(Call<BaseEntity<Object>> call, Response<BaseEntity<Object>> response) {
                    if(response!=null&&response.body()!=null) {
                        showloading_diag.postValue(3);
                    }else{
                        showloading_diag.postValue(2);
                        toast_message.postValue(response.message());
                    }

                }

                @Override
                public void onFailure(Call<BaseEntity<Object>> call, Throwable t) {
                    showloading_diag.postValue(2);
                    toast_message.postValue(t.getMessage());

                }
            });
            return;

        }
        APIManager.getInstance().getNeedAPI().publishNeedMessage(map).enqueue(new Callback<BaseEntity<Object>>() {
            @Override
            public void onResponse(Call<BaseEntity<Object>> call, Response<BaseEntity<Object>> response) {

                if(response!=null&&response.body()!=null) {
                    showloading_diag.postValue(3);
                }else{
                    showloading_diag.postValue(2);
                    toast_message.postValue(response.message());
                }

            }

            @Override
            public void onFailure(Call<BaseEntity<Object>> call, Throwable t) {
                showloading_diag.postValue(2);
                toast_message.postValue(t.getMessage());

            }
        });

    }

    /**
     * 选择行业类型
     */
    public void getIndustry_type(){

        if(industry_type_list.size()>0){
            showchoicepopwindow.postValue(1);
            return;
        }

        showloading_diag.postValue(1);
        APIManager.getInstance().getNeedAPI().getAllSserviceCategory().enqueue(new Callback<BaseEntity<List<Bean>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<Bean>>> call, Response<BaseEntity<List<Bean>>> response) {
                showloading_diag.postValue(2);
                if(response!=null&&response.body()!=null&&response.body().getData()!=null){
                    industry_type_list.addAll(response.body().getData());
                }
                if(industry_type_list.size()>0){
                    showchoicepopwindow.postValue(1);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<Bean>>> call, Throwable t) {
                showloading_diag.postValue(2);
                toast_message.postValue(t.getMessage());
            }
        });


    }

    /**
     * 选择企业类型
     */
    public void getnterprise_type(){




        showchoicepopwindow.postValue(2);
    }

    /**
     * 选择注册地址
     */
    public void getRegist_path(){

        if(datas!=null&&datas.size()>0){
            showchoicepopwindow.postValue(3);
            return;
        }
        showloading_diag.postValue(1);
        APIManager.getInstance().getGoodsAPI().getCityList().enqueue(new Callback<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>> call, Response<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>> response) {
                showloading_diag.postValue(2);
                datas = response.body().getData();
                showchoicepopwindow.postValue(3);
            }

            @Override
            public void onFailure(Call<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>> call, Throwable t) {
                showloading_diag.postValue(2);
            }
        });

    }

    /**
     * 选择纳税规模
     */
    public void getTaxscale(){

        showchoicepopwindow.postValue(4);
    }



    public void setdata(){
        if(!TextUtils.isEmpty(data.getDemandTitle())){
            name.postValue(data.getDemandTitle());
        }
        if(!TextUtils.isEmpty(data.getIndustryTypeName())){
            industry_type.postValue(data.getIndustryTypeName());
        }
        if(!TextUtils.isEmpty(data.getIndustryTypeId())){
            industry_type_id = data.getIndustryTypeId();
        }
        if(!TextUtils.isEmpty(data.getEnterpriseTypeName())){
            enterprise_type.postValue(data.getEnterpriseTypeName());
        }
        if(!TextUtils.isEmpty(data.getEnterpriseTypeId())){
            enterprise_type_index = Integer.parseInt(data.getEnterpriseTypeId());
            enterprise_type.postValue(enterprise_type_list.get(enterprise_type_index).getPickerViewText());
        }
        if(!TextUtils.isEmpty(data.getRegisteredAddr())){
            regist_path.postValue(data.getRegisteredAddr());
            try {

                StringBuilder stringBuilder = new StringBuilder();
                JSONObject jsonObject = JSONObject.parseObject(data.getRegisteredAddr());
                if(jsonObject.get("provinceId")!=null){
                    provinceNo = jsonObject.getString("provinceId");
                }
                if(jsonObject.get("provinceName")!=null){
                    provinceName  = jsonObject.getString("provinceName");
                    stringBuilder.append(provinceName);
                }
                if(jsonObject.get("cityId")!=null){
                    cityNo = jsonObject.getString("cityId");
                }
                if(jsonObject.get("cityName")!=null){
                    cityName = jsonObject.getString("cityName");
                    stringBuilder.append("-").append(cityName);
                }
                if(jsonObject.get("areaId")!=null){
                    districtNo = jsonObject.getString("areaId");
                }
                if(jsonObject.get("areaName")!=null){
                    areaName = jsonObject.getString("areaName");
                    stringBuilder.append("-").append(areaName);
                }

                regist_path.postValue(stringBuilder.toString());
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        if(!TextUtils.isEmpty(data.getTaxReturns())){
            taxreturns_normal.postValue(data.getTaxReturns().indexOf("1")>-1);
            taxreturns_abnormal.postValue(data.getTaxReturns().indexOf("0")>-1);
        }

        if(!TextUtils.isEmpty(data.getTaxScale())){
            taxScale_data = data.getTaxScale();

            if(data.getTaxScale().indexOf(",")>-1){
                String text_data = "";
                String[] ids = data.getTaxScale().split(",");
                for (String id : ids) {
                    if(!TextUtils.isEmpty(gettype(id))) {
                        text_data = text_data + gettype(id) + ",";
                    }
                }
                taxscale.postValue(text_data.substring(0,text_data.length()-1));
            }else{
                taxscale.postValue(gettype(data.getTaxScale()));
            }
        }

        if(data.getBudgetPrice()>0){
            money.postValue(PointUtils.price(data.getBudgetPrice()));
            is_bargaining.postValue(false);
        }else{
            is_bargaining.postValue(true);
        }

        if(!TextUtils.isEmpty(data.getLinkman())){
            contacts_name.postValue(data.getLinkman());
        }
        if(!TextUtils.isEmpty(data.getLinkmanPhone())){
            contacts_phone.postValue(data.getLinkmanPhone());
        }
        if(!TextUtils.isEmpty(data.getSpecifications())){
            need_content.postValue(data.getSpecifications());
        }
        if(!TextUtils.isEmpty(data.getNote())){
            need_remarks.postValue(data.getNote());
        }

    }

    private String gettype(String s){
        String m = "";
        if(!TextUtils.isEmpty(s)){
            if(s.equals("0")){
                m = "小规模";
            }else if(s.equals("1")){
                m = "一般纳税人";
            }else if(s.equals("2")){
                m = "出口纳税人";
            }else if(s.equals("3")){
                m = "未核税";
            }
        }
        return m;
    }


    public void Deleteregistpath(){
        cityName = "";
        cityNo = "";
        provinceName = "";
        provinceNo = "";
        areaName = "";
        districtNo = "";
        regist_path.postValue("");
    }

}
